package nio.aioTimeServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2017/3/15 0015.
 */
public class ATimeClient {
    private static final byte[] req;

    static
    {
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<100; i++)
        {
            sb.append("This is a request.");
        }
        req = sb.toString().getBytes();
    }

    private static final byte[] resp = new byte[13000];

    public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException
    {
        int port = 1234;
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName("localhost"), port));
        final InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();

        new Thread ()
        {
            public void run()
            {
                long startTime = System.currentTimeMillis();
                int loopTimes = 1;
                for (;; loopTimes++)
                {
                    try
                    {
                        int len = is.read(resp); //不一定会读满
                        for (; len<resp.length;)
                        {
                            len += is.read(resp, len-1, resp.length-len);
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                        break;
                    }
//                    System.out.println(new String(b));
                    System.out.println("-" + loopTimes);
                    if (loopTimes == 30000)
                    {
                        System.out.println("time cost : " + (System.currentTimeMillis() - startTime));
                    }
                }
            }
        }.start();

        for (int i = 0; i< 30000; i++)
        {
            os.write(req);
//            os.flush();
            System.out.println("written");
            Thread.sleep(1);
        }
    }
}
